package zk.tool.util;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import org.apache.zookeeper.KeeperException;
import zk.tool.ZKClient;
import zk.tool.component.NodeItem;
import zk.tool.handler.TreeItemExpandHandler;
import zk.tool.model.TreeItemData;

import java.util.ArrayList;
import java.util.List;

public class TreeCommon {

    public static void refreshData(ZKClient client, TreeItem<TreeItemData> item) throws InterruptedException, KeeperException {
        if (item == null || client == null) {
            return;
        }
        TreeItemData itemData = item.getValue();
        if (itemData == null) {
            return;
        }

        TreeItemData data = client.getData(itemData.getPath());
        itemData.setData(data.getData());
        itemData.setStat(data.getStat());
        itemData.setDataLoaded(true);
    }

    public static void refreshChildren(ZKClient client, TreeItem<TreeItemData> item)
            throws InterruptedException, KeeperException {
        ObservableList<TreeItem<TreeItemData>> children = item.getChildren();
        Platform.runLater(() -> {
            children.clear();
            children.add(new TreeItem<>(new TreeItemData("", "加载中...")));
        });
        List<TreeItem<TreeItemData>> items = loadChildren(client, item.getValue().getPath());
        Platform.runLater(() -> {
            item.getValue().setChildrenLoaded(true);
            children.clear();
            children.addAll(items);
        });
    }

    public static List<TreeItem<TreeItemData>> loadChildren(ZKClient client, String path)
            throws InterruptedException, KeeperException {
        List<String> children = client.getChildren(path);
        List<TreeItem<TreeItemData>> items = new ArrayList<>();
        for (String name : children) {
            NodeItem nodeItem;
            if (path.endsWith("/")) {
                nodeItem = new NodeItem(new TreeItemData(path + name, name));
            } else {
                nodeItem = new NodeItem(new TreeItemData(path + "/" + name, name));
            }
            nodeItem.addEventHandler(TreeItem.branchExpandedEvent(), new TreeItemExpandHandler(client));
            items.add(nodeItem);
        }
        return items;
    }
}
